<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="JinYan&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/blog/css/images/logo.jpg">
  
  <title>
    
      Python-3-错误和异常 | SanYuanEmpire
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/blog/css/style.css">
<link rel="stylesheet" href="/blog/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/blog/js/qrious.js"></script>
<script src="/blog/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.jpg" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/blog/">
      <div class="logo"></div>
      <span>SanYuanEmpire</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/blog/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/blog/archives/" class="item-link">Archives</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/blog/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/blog/archives/" class="menu-link">Archives</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Python-3-错误和异常</h2>
  <p class="post-date">2018-09-03</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="错误和异常"><a href="#错误和异常" class="headerlink" title="错误和异常"></a>错误和异常</h1><h2 id="语法错误"><a href="#语法错误" class="headerlink" title="语法错误"></a>语法错误</h2><ul>
<li>SyntaxError 类表示语法错误，当解释器发现代码无法通过语法检查时会触发的错误。语法错误是无法用 try…except…捕获的。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; print:</span><br><span class="line">  File &quot;&quot;, line 1</span><br><span class="line">    print:</span><br><span class="line">         ^</span><br><span class="line">SyntaxError: invalid syntax</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h2><ul>
<li>即便程序的语法是正确的，在运行它的时候，也有可能发生错误。运行时发生的错误被称为异常。 错误信息的前面部分显示了异常发生的上下文，并以调用栈的形式显示具体信息。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; 1 + &apos;0&apos;</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File &quot;&quot;, line 1, in </span><br><span class="line">TypeError: unsupported operand type(s) for +: &apos;int&apos; and &apos;str&apos;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h1><blockquote>
<p>Python 提供了 try … except … 的语法结构来捕获和处理异常。</p>
</blockquote>
<p><img src="http://wx2.sinaimg.cn/mw690/705e8c43gy1fuw5flm1woj20md0gbjs6.jpg" alt="try 语句执行流程大致如下"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">首先，执行 try 子句（在关键字 try 和关键字 except 之间的语句）</span><br><span class="line">如果没有异常发生，忽略 except 子句，try 子句执行后结束。</span><br><span class="line">如果在执行 try 子句的过程中发生了异常，那么 try 子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符，那么对应的 except 子句将被执行。最后执行 try 语句之后的代码。</span><br><span class="line">如果一个异常没有与任何的 except 匹配，那么这个异常将会传递给上层的 try 中。</span><br><span class="line">一个 try 语句可能包含多个 except 子句，分别来处理不同的特定的异常。</span><br><span class="line">最多只有一个 except 子句会被执行。</span><br><span class="line">处理程序将只针对对应的 try 子句中的异常进行处理，而不是其他的 try 的处理程序中的异常。</span><br><span class="line">一个 except 子句可以同时处理多个异常，这些异常将被放在一个括号里成为一个元组。</span><br><span class="line">最后一个 except 子句可以忽略异常的名称，它将被当作通配符使用。可以使用这种方法打印一个错误信息，然后再次把异常抛出。</span><br><span class="line">try except 语句还有一个可选的 else 子句，如果使用这个子句，那么必须放在所有的 except 子句之后。这个子句将在 try 子句没有发生任何异常的时候执行。</span><br><span class="line">异常处理并不仅仅处理那些直接发生在 try 子句中的异常，而且还能处理子句中调用的函数（甚至间接调用的函数）里抛出的异常。</span><br><span class="line">不管 try 子句里面有没有发生异常，finally 子句都会执行。</span><br><span class="line">如果一个异常在 try 子句里（或者在 except 和 else 子句里）被抛出，而又没有任何的 except 把它截住，那么这个异常会在 finally 子句执行后再次被抛出。</span><br></pre></td></tr></table></figure>
<h1 id="抛出异常"><a href="#抛出异常" class="headerlink" title="抛出异常"></a>抛出异常</h1><blockquote>
<p>使用 raise 语句抛出一个指定的异常。<br>raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类（也就是 Exception 的子类）。<br>如果你只想知道这是否抛出了一个异常，并不想去处理它，那么一个简单的 raise 语句就可以再次把它抛出。</p>
</blockquote>
<h1 id="自定义异常"><a href="#自定义异常" class="headerlink" title="自定义异常"></a>自定义异常</h1><blockquote>
<p>可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类，可以直接继承，或者间接继承。<br>当创建一个模块有可能抛出多种不同的异常时，一种通常的做法是为这个包建立一个基础异常类，然后基于这个基础类为不同的错误情况创建不同的子类。<br>大多数的异常的名字都以”Error”结尾，就跟标准的异常命名一样。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">实例</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Error</span><span class="params">(Exception)</span>:</span></span><br><span class="line">    <span class="string">"""Base class for exceptions in this module."""</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="comment"># 自定义异常</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InputError</span><span class="params">(Error)</span>:</span></span><br><span class="line">    <span class="string">"""Exception raised for errors in the input.</span></span><br><span class="line"><span class="string">    Attributes:</span></span><br><span class="line"><span class="string">        expression -- input expression in which the error occurred</span></span><br><span class="line"><span class="string">        message -- explanation of the error</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, expression, message)</span>:</span></span><br><span class="line">        self.expression = expression</span><br><span class="line">        self.message = message</span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    print(<span class="string">'code start running...'</span>)</span><br><span class="line">    <span class="keyword">raise</span> InputError(<span class="string">'input()'</span>, <span class="string">'input error'</span>)</span><br><span class="line">    <span class="comment"># ValueError</span></span><br><span class="line">    int(<span class="string">'a'</span>)</span><br><span class="line">    <span class="comment"># TypeError</span></span><br><span class="line">    s = <span class="number">1</span> + <span class="string">'a'</span></span><br><span class="line">    dit = &#123;<span class="string">'name'</span>: <span class="string">'john'</span>&#125;</span><br><span class="line">    <span class="comment"># KeyError</span></span><br><span class="line">    print(dit[<span class="string">'1'</span>])</span><br><span class="line"><span class="keyword">except</span> InputError <span class="keyword">as</span> ex:</span><br><span class="line">    print(<span class="string">"InputError:"</span>, ex.message)</span><br><span class="line"><span class="keyword">except</span> TypeError <span class="keyword">as</span> ex:</span><br><span class="line">    print(<span class="string">'TypeError:'</span>, ex.args)</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="keyword">except</span> (KeyError, IndexError) <span class="keyword">as</span> ex:</span><br><span class="line">    <span class="string">"""支持同时处理多个异常, 用括号放到元组里"""</span></span><br><span class="line">    print(sys.exc_info())</span><br><span class="line"><span class="keyword">except</span>:</span><br><span class="line">    <span class="string">"""捕获其他未指定的异常"""</span></span><br><span class="line">    print(<span class="string">"Unexpected error:"</span>, sys.exc_info()[<span class="number">0</span>])</span><br><span class="line">    <span class="comment"># raise 用于抛出异常</span></span><br><span class="line">    <span class="keyword">raise</span> RuntimeError(<span class="string">'RuntimeError'</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="string">"""当无任何异常时, 会执行 else 子句"""</span></span><br><span class="line">    print(<span class="string">'"else" 子句...'</span>)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    <span class="string">"""无论有无异常, 均会执行 finally"""</span></span><br><span class="line">    print(<span class="string">'finally, ending'</span>)</span><br></pre></td></tr></table></figure></p>
</blockquote>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/blog/2018/09/03/Python-3-模块/">
        <span class="nav-arrow">← </span>
        
          Python-3-模块
        
      </a>
    
    
      <a class="nav-right" href="/blog/2018/09/03/Python-3-面向对象/">
        
          Python-3-面向对象
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#错误和异常"><span class="toc-nav-text">错误和异常</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#语法错误"><span class="toc-nav-text">语法错误</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#异常"><span class="toc-nav-text">异常</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#异常处理"><span class="toc-nav-text">异常处理</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#抛出异常"><span class="toc-nav-text">抛出异常</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#自定义异常"><span class="toc-nav-text">自定义异常</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'git@gitee.com:sanyuanempire/blog.git/2018/09/03/Python-3-错误和异常/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Python-3-错误和异常",
        owner: "",
        repo: "",
        oauth: {
          client_id: "",
          client_secret: ""
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'git@gitee.com:sanyuanempire/blog.git/2018/09/03/Python-3-错误和异常/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2018 | Proudly powered by <a href="https://sanyuanempire.gitee.io/blog" target="_blank">JinYan</a>
    <br>
    Theme by <a href="https://sanyuanempire.gitee.io/blog">JinYan</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/blog/js/script.js"></script>

  </body>
</html>